<template>
  <div class="login-container">
    <el-form
      ref="ruleFormRef"
      class="login-form"
      :model="compState"
      :rules="rules"
      status-icon
    >
      <div class="logo">
        <!-- 图片 -->
        <!-- <img src="../../../public/images/login/anchor.png" alt="" style="margin-top:130px" /> -->
        <!-- <img src="../../../public/images/login/login-logo.png" alt="" /> -->
        <!-- <img class="login-logo-yc" src="../../../public/images/login/login-logo_yc.png" alt="" /> -->
        <!-- <img
          class="login-logo-yc"
          src="../../../public/images/login/login-logo_dxhd.png"
          alt=""
        /> -->
        <img
          class="login-logo-yc"
          src="../../../public/images/login/login-logo_haerb.png"
          alt=""
        />
      </div>
      <div class="title-container">
        <!-- <span class="title">亚运智能医疗急救保障系统</span> -->
        <!-- <span class="title">亚残运会智能医疗急救保障系统</span> -->
        <!-- <span class="title">大型活动医疗急救保障系统</span> -->
        <!-- <span class="title">安克赛事活动保障系统</span> -->
        <span class="title">哈尔滨亚冬医疗急救保障系统</span>
      </div>
      <!-- 用户名 -->
      <el-form-item prop="WorkCode">
        <el-input
          type="text"
          placeholder="请输入用户名"
          name="WorkCode"
          v-model="compState.WorkCode"
          clearable
          :prefix-icon="UserFilled"
          size="large"
        ></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item prop="PassWord">
        <el-input
          type="password"
          show-password
          placeholder="请输入密码"
          name="PassWord"
          v-model="compState.PassWord"
          :prefix-icon="Lock"
          clearable
          size="large"
        >
        </el-input>
      </el-form-item>
      <el-form-item
        prop="verificationCodeInpt"
        v-if="compState.whetherOpenIconCode"
      >
        <div style="display: flex">
          <el-input
            type="text"
            placeholder="请输入图形码"
            name="verificationCodeInpt"
            v-model="compState.verificationCodeInpt"
            :prefix-icon="Key"
            clearable
            size="large"
          >
          </el-input>
          <s-identify :identifyCode="compState.verificationCode"></s-identify
          >&nbsp;&nbsp;
          <el-button type="" @click="handleRefreshVerificationCode"
            >刷新图形码</el-button
          >
        </div>
      </el-form-item>
      <!-- 手机验证码 -->
      <!-- <el-form-item prop="ValidCode">
        <el-input type="text" placeholder="请输入手机验证码" name="ValidCode" v-model="compState.ValidCode" clearable
          size="large">
          <template #append>
            <el-button :type="compState.isDisposed ? 'info' : ''" @click="getValidCode" :disabled="compState.isDisposed">
              {{ compState.isDisposed ? `${compState.dtime}s后重新获取` : "获取验证码" }}
            </el-button>
          </template>
        </el-input>
      </el-form-item> -->
      <!-- 登录按钮 -->
      <el-form-item>
        <el-button
          class="loginBtn"
          type="primary"
          @click="submitForm(ruleFormRef)"
          size="large"
        >
          {{ $t(`${''}login.title`) }}
        </el-button>
        <!-- <el-button type="" @click="Ceshi">测试</el-button> -->
      </el-form-item>
    </el-form>
    <!-- <iframe :src="compState.cockpiturl" width="100px" height="100px"></iframe> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { UserFilled, Lock, Key } from '@element-plus/icons-vue';
import { GetRandomNumber } from '../../network/login';
import { ElMessage } from 'element-plus';
import { GM_SM4Encrypt, GM_SM4Decrypt } from '../../utils/sm4Import';
// 图形验证码
import SIdentify from './component/SIdentify.vue';
import { useStore } from 'vuex';
import axios from 'axios';

const store = useStore();
const ruleFormRef = ref();
const compState = reactive({
  WorkCode: '',
  PassWord: '',
  ValidCode: '',
  temporaryValidCode: 0,
  isDisposed: false,
  dtime: 60,
  verificationCodeInpt: '',
  verificationCode: '1234',
  verificationCodes: '1234567890',
  whetherOpenIconCode: false,
  cockpiturl: '',
});

const validateWorkCode = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名（工号）!'));
  } else {
    callback();
  }
};

const validatePassWord = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码!'));
  } else {
    // 至少包含一个大写字母/小写字母/数字,至少8位可以包含特殊字符
    var pattern = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d@$!%*#?&._]{8,}$/;
    let isPassPassWord = pattern.test(compState.PassWord);
    if (isPassPassWord) {
      callback();
    } else {
      callback(new Error('密码输入规则有误!'));
    }
  }
};

// 图形验证码验证
const validateVerificationCodeInpt = (rule, value, callback) => {
  if (compState.whetherOpenIconCode) {
    if (value === '') {
      callback(new Error('请输入图形验证码!'));
    } else {
      if (compState.verificationCode === compState.verificationCodeInpt) {
        callback();
      } else {
        callback(new Error('验证码输入不一致，请重新输入！'));
      }
    }
  } else {
    callback();
  }
};

// 手机验证码
const validateValidCode = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入验证码!'));
  } else {
    if (Number(compState.ValidCode) === compState.temporaryValidCode) {
      callback();
    } else {
      // console.log("12---",compState.ValidCode,compState.temporaryValidCode)
      callback(new Error('验证码错误!'));
    }
  }
};

const rules = reactive({
  WorkCode: [{ validator: validateWorkCode, trigger: 'blur' }],
  PassWord: [{ validator: validatePassWord, trigger: 'blur' }],
  verificationCodeInpt: [
    { validator: validateVerificationCodeInpt, trigger: 'blur' },
  ],
  //  ValidCode: [{ validator: validateValidCode, trigger: 'blur' }],
});

// 获取手机验证码
const getValidCode = () => {
  if (compState.WorkCode) {
    GetRandomNumber({ WorkCode: compState.WorkCode })
      .then((res) => {
        if (res) {
          // console.log(res)
          compState.temporaryValidCode = 0; //重置缓存
          compState.isDisposed = true;
          handleTimeChange();
          compState.temporaryValidCode = res;
        } else {
          console.log(res);
        }
      })
      .catch((err) => {
        console.log('获取验证码失败！', err);
      });
  } else {
    ElMessage({
      type: 'warning',
      message: '账号不能为空！',
    });
  }
};
const handleTimeChange = () => {
  if (compState.dtime <= 0) {
    compState.isDisposed = false;
    compState.dtime = 60;
  } else {
    setTimeout(() => {
      compState.dtime--;
      handleTimeChange();
    }, 1000);
  }
};

// 刷新图形验证码
const handleRefreshVerificationCode = () => {
  compState.verificationCode = '';
  makeCode(compState.verificationCodes, 4);
};
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    compState.verificationCode += o[randomNum(i, o.length)];
  }
};
const randomNum = (min, max) => {
  return Math.floor(Math.random() * (max - min) + min);
};

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      compState.temporaryValidCode = 0; //重置缓存
      let encryptPasswordData = GM_SM4Encrypt(compState.PassWord);
      // compState.PassWord = encryptPasswordData
      let pw = encryptPasswordData;
      // console.log(pw)
      // console.log(encryptPasswordData)
      store.dispatch('app/login', {
        WorkCode: compState.WorkCode,
        PassWord: pw,
      });
    } else {
      console.log('error submit!!');
      console.log('aaStr', JSON.stringify(aaStr));
      let aaStrEn = GM_SM4Encrypt(JSON.stringify(aaStr));
      console.log(aaStrEn);
      let aaStrDe = JSON.parse(GM_SM4Decrypt(aaStrEn));
      console.log(aaStrDe);
      return false;
    }
  });
};

var keydownLogin = (keydown) => {
  // console.log(keydown)
  if (keydown.key == 'Enter') submitForm(ruleFormRef.value);
};

// ceshi1
const Ceshi = async () => {
  let encryptFlagData = GM_SM4Encrypt('Anchor120...');
  await axios
    .post(`/cockpit/Home/UserLoginByInfo?lgFlag=${encryptFlagData}`)
    .then((res) => {
      console.log(res);
      if (res != null && res != '') {
        compState.cockpiturl = `/cockpit${res.data}&Flag=${encryptFlagData}`;
        console.log(compState.cockpiturl);
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
onMounted(() => {
  console.log('登录页加载！');
  // 是否启用图形验证码
  // console.log(aaStr)
  // let aa = GM_SM4Encrypt(JSON.stringify(aaStr))
  // console.log(aa)
  // console.log(JSON.parse(GM_SM4Decrypt(aa)))
  let configParamStrDec = JSON.parse(GM_SM4Decrypt(paramsStr));
  console.log(
    'configParamStrDec.whetherOpenIconCode',
    configParamStrDec.whetherOpenIconCode,
  );
  compState.whetherOpenIconCode = configParamStrDec.whetherOpenIconCode;
  // 初始化验证码
  if (compState.whetherOpenIconCode) {
    compState.verificationCode = '';
    makeCode(compState.verificationCodes, 4);
  }
  window.addEventListener('keydown', keydownLogin);
});
onUnmounted(() => {
  console.log('登录页清除键盘事件监听！');
  window.removeEventListener('keydown', keydownLogin);
});
</script>

<style lang="scss" scoped>
$bgColor: #f2f5f8;
$cursor: #fff;

.login-container {
  width: 100%;
  height: 100vh;
  // background: url('../../../public/images/login/login.png');
  // background: url("../../../public/images/login/login_yc.png");
  // background: url("../../../public/images/login/login_dxhd.png");
  background: url('../../../public/images/login/login_bg.png');

  background-size: cover;

  .login-form {
    background-color: #fff;
    position: absolute;
    width: 400px;
    right: 10%;
    bottom: 50px;
    padding: 30px;
    text-align: center;

    .loginBtn {
      width: 100%;
      background-color: #8172d5;
    }
  }

  .title-container {
    position: relative;
    text-align: center;
    height: 100px;

    .title {
      font-family: 'Microsoft YaHei-Bold';
      font-size: 26px;
      text-align: center;
      font-weight: bold;
      line-height: 100px;
    }
  }
}
.login-logo-yc {
  width: 300px;
  height: 230px;
}
</style>
